import sys, re, csv

class Question(dict):
    '''A Question class for storing metadata for quiz bowl questions.

    Questions contain six pieces of information: an identifier number,
    a text attribution, two categories - a general and a specific, the
    text of a question, and the text of the answer.

    The data is stored internally inside a dictionary.'''

    ID = 1

    def __init__(self, year, level, author,
                 gen_category, spec_category,
                 question, answer):
        '''
        Default constructor for a Question.

        Arguments:
        attribution - a String containing the packet/authors of question
        question - a String with the text of the question
        gen_category - a String representing the general category of the q
        spec_category - a String representing the specific category of the q
        answer - a String representing the question\'s answer

        "Question" class will automatically determine the new Question\'s
        unique ID number based on a static class variable. It will also
        convert "answer" into a list of acceptable answers.
        '''
        
        self['year'] = year
        self['level'] = level
        self['author'] = author
        self['question'] = question
        self['gen_category'] = gen_category
        self['spec_category'] = spec_category
        self['answer'] = answer
        self['id'] = Question.ID

        Question.ID += 1

    def __setitem__(self, key, item):
        '''
        Overrides the default behavior for __setitem__; we need to
        worry about when an answer is added to the question, because
        we want it converted into a list of acceptable answers.
        '''
        if ((key == "answer") and item):
            item = self.__parseAnswer(item)
        dict.__setitem__(self, key, item)
            
    def __parseAnswer(self, answer):
        '''
        Parses a string containing the answer to a question.

        Arguments:
        answer - a string containing the answer

        Returns:
        a list containing all the strings that are acceptable
         answers to the question
        '''
        #newAnswer = [answer, ]
        newAnswer = answer
        return newAnswer


def read_question_file(filename):
    try:
        file = open(filename, 'r')
    except IOError:
        print "There was an error reading the file"
        sys.exit(1)

    lines = file.readlines()[1:]
   
    questionData = None
    questions = []
    
    order = 1
    for line in lines:
        line = line.strip()
        if (line != ''):
            
            if (order == 1):
                questionData = dict()
                attPattern = re.compile(r'^(?P<year>\d{4}).ACF.(?P<level>\w+).+by.(?P<author>[\w\s]+)')
                match = re.match(attPattern, line)
                matchDict = match.groupdict()
                
                questionData['year'] = int(matchDict['year'])
                questionData['author'] = matchDict['author'].strip()
                questionData['level'] = matchDict['level'].lower()
                
                order = order+1
            elif (order == 2):
                bits = line.split('--')
                questionData['gen_category'] = bits[0].strip()
                questionData['spec_category'] = bits[-1].strip()
                order = order+1
            elif (order == 3):
                #question = line.replace('"', '""')
                ## naively cut off escape characters to ensure
                ## ASCII encoding works later
                question = "".join(i for i in line if ord(i)<128)
                questionData['question'] = question.strip()
                order = order+1
            elif (order == 4):
                fullAnswer = line.split(':')[-1].strip()
                specificAnswer = fullAnswer.split(" (prompt")[0]
                ##specificAnswer = specificAnswer.replace('"', '""')
                ## naively cut off escape characters to ensure
                ## ASCII encoding works later
                specificAnswer = "".join(i for i in specificAnswer if ord(i)<128)
                questionData['answer'] = specificAnswer
                
                order = 1

                questions.append(Question(**questionData))
                questionData = None

    return questions
    
if __name__ == '__main__':

    filename = raw_input("Please enter a filename to read: ")
    questions = read_question_file(filename)
    
    out_file = open('qbdb.csv', 'w')
    
    fieldnames = ['year', 'author', 'level', 'gen_category', 'spec_category',
                  'question', 'answer', 'id']
    dwriter = csv.DictWriter(out_file, fieldnames)
    dwriter.writerows(questions)
    
    out_file.close()
    
    
    


